"""
Case Type   : 多节点写入
Case Name   : 备机在事务中执行批量插入
Create At   : 2023/1/9
Owner       : @li-xin12345
Description :
    1.修改enable_remote_execute参数值为on
    2.将备机降级为级联备
    3.在级联备创建表
    4.级备机查看日志打印
    5.在主机创建表
    6.在级联备执行DML写语句
    7.环境清理，恢复参数
Expect      :
    1.修改成功
    2.降级成功
    3.执行失败，合理报错
    4.级联备日志记录建立连接、转发给备机、接受执行结果等libpqsw信息，备机直接执行，不再转发给主机
    5.创建成功
    6.执行失败，合理报错
    7.环境清理成功，恢复参数成功
History     :
    Modified by @haomeng802 2023/6/29:研发代码变更，log信息发生变化，优化断言以适配新代码
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table_name = 't_multi_node_write_0037'
        self.new_log_path = os.path.join(macro.PG_LOG_PATH,
                                         'pg_log_multi_node_write_case0037')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, '执行失败' + step1)
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, '执行失败' + step1)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', '执行失败' + step1)
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, '执行失败' + step1)
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', '执行失败' + step1)

        step2 = "-----step2:将备机降级为级联备;expect:降级成功-----"
        self.logger.info(step2)
        build_res = self.standby_sh.build_standby('-M cascade_standby')
        self.assertIn(self.constant.REBUILD_SUCCESS_MSG, build_res,
                      '执行失败:' + step2)
        refresh_res = self.standby_sh.exec_refresh_conf()
        self.assertTrue(refresh_res, '执行失败:' + step2)
        time.sleep(4)
        status_res = self.standby_sh.get_db_cluster_status('status')
        self.assertTrue(status_res, '执行失败:' + step2)
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.new_log_path}\'', single=True)
        self.assertTrue(result, '修改参数失败:' + self.log_directory)
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_path,
                          '修改参数失败:' + self.log_directory)

        step3 = "-----step3:在级联备创建表;expect:执行失败，合理报错-----"
        self.logger.info(step3)
        create_cmd = f'''drop table if exists {self.table_name};
                    create table {self.table_name}(id int,name varchar(20));'''
        create_msg = self.standby_sh.execut_db_sql(create_cmd)
        self.logger.info(create_msg)
        self.assertIn(f'ERROR:  cannot execute '
                      f'{self.constant.TABLE_DROP_SUCCESS} in a '
                      f'read-only transaction', create_msg, '执行失败' + step3)
        self.assertIn(f'ERROR:  cannot execute '
                      f'{self.constant.TABLE_CREATE_SUCCESS} in a '
                      f'read-only transaction', create_msg, '执行失败' + step3)
        time.sleep(2)

        step4 = "-----step4:级备机查看日志打印;expect:级联备日志记录建立连接、" \
                "转发给备机、接受执行结果等libpqsw信息，备机直接执行，不再转发给主机-----"
        self.logger.info(step4)
        shell_cmd = f"ls -t {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_path, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('we find new transfer request',
                      shell_msg, '执行失败:' + step4)
        self.assertIn('Connecting to remote server',
                      shell_msg, '执行失败:' + step4)

        step5 = "-----step5:在主机创建表;expect:创建成功-----"
        self.logger.info(step5)
        create_msg = PrimarySh.execut_db_sql(create_cmd)
        self.logger.info(create_msg)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      create_msg, '执行失败' + step5)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS,
                      create_msg, '执行失败' + step5)
        time.sleep(2)

        step6 = "-----step6:在级联备执行DML写语句;expect:执行失败，合理报错-----"
        self.logger.info(step6)
        sql_cmd = f'''insert into {self.table_name} values
            (generate_series(1,10), 'test');
            update {self.table_name} set name='software' where id = 3;
            delete from {self.table_name} where id=5;
            select * from {self.table_name};'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(f'ERROR:  cannot execute '
                      f'{self.constant.INSERT_SUCCESS_MSG} in a '
                      f'read-only transaction', sql_msg, '执行失败' + step6)
        self.assertIn(f'ERROR:  cannot execute '
                      f'{self.constant.UPDATE_SUCCESS_MSG} in a '
                      f'read-only transaction', sql_msg, '执行失败' + step6)
        self.assertIn(f'ERROR:  cannot execute '
                      f'{self.constant.DELETE_SUCCESS_MSG} in a '
                      f'read-only transaction', sql_msg, '执行失败' + step6)
        self.assertIn('(0 rows)', sql_msg, '执行失败' + step6)

    def tearDown(self):
        step7 = "-----step7:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step7)
        build_res = self.standby_sh.build_standby('-M standby')
        refresh_res = self.standby_sh.exec_refresh_conf()
        time.sleep(4)
        status_res = self.standby_sh.get_db_cluster_status('status')
        drop_cmd = f"drop table {self.table_name};"
        drop_msg = PrimarySh.execut_db_sql(drop_cmd)
        self.logger.info(drop_msg)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.log_dir_default}\'', single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.logger.info("-----断言teardown-----")
        self.assertIn(self.constant.REBUILD_SUCCESS_MSG, build_res,
                      '执行失败:' + step7)
        self.assertTrue(refresh_res, '执行失败:' + step7)
        self.assertTrue(status_res, '执行失败:' + step7)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_msg, '执行失败' + step7)
        self.assertTrue(result1, '执行失败' + step7)
        self.assertTrue(restart_res, '执行失败' + step7)
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          '执行失败' + step7)
        self.assertTrue(result2, '执行失败' + step7)
        self.assertTrue(result3, '执行失败' + step7)
        self.assertEquals(show_log_statement, self.log_statement_default,
                          '执行失败' + step7)
        self.assertEquals(show_log_directory, self.log_dir_default,
                          '执行失败' + step7)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
